package linke.study.spring.app;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import linke.study.spring.service.SecurityService;
import linke.study.spring.service.UserService;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Application {
	
	private static ApplicationContext appCtx;
	
	private static void simulateRequest(final String methodName) {
		new Thread(new Runnable(){
			public void run() {
				Method method;
				try {
					method = Application.class.getDeclaredMethod(methodName, new Class[0]);
					method.invoke(null, new Object[0]);
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	public static void main(String[] args) {
		appCtx = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml", "applicationContext-aop.xml"});
		simulateRequest("nomalUserRequest");
		randomSleep(8);
	}

	public static void nomalUserRequest(){
		SecurityService ss = appCtx.getBean(SecurityService.class);
		ss.doUserLogin("linke", "41451");
		randomSleep(15);
		ss.doUserLogout("linke");
		ss.doUserLogin(null, null);
	}
	
	public static void adminRequest(){
		UserService us = appCtx.getBean(UserService.class);
		us.addUser();
		randomSleep(5);
		us.addUser();
		randomSleep(5);
		us.addUser();
		randomSleep(5);
		us.removeUser(1L);
		randomSleep(5);
	}
	
	private static void randomSleep(int whinSecRange) {
		try {
			Thread.sleep((long)(1000 * (1 + whinSecRange * Math.random())));
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
